package disk;

import group.GeoGroup;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.vecmath.Point3d;

import buildtools.Connector;

import math.Spherical;
import node.GeoNode;

import component.Ball;
import component.ComponentFactory;
import component.Structure;
import component.Tube;

public class Load {
	private DataInputStream in;
	private Structure structure;
	private ComponentFactory factory;
	
	public Load(Structure structure, ComponentFactory factory) {
		this.structure = structure;
		this.factory = factory;
	}
	
	public void load() throws IOException {
		File file = chooseFile();
		loadFile(file);		
	}

	private File chooseFile() {
		final JFileChooser fc = new JFileChooser();
		int returnVal = fc.showOpenDialog(null);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			return fc.getSelectedFile();
		}
		return null;
	}

	private void loadFile(File file) throws IOException {
		in = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
		clearGroup();
		readGroup();
		connectAll();
		in.close();
	}

	private void connectAll() {
		Connector connector = new Connector(structure);
		connector.connectAllPossible();
	}

	private void clearGroup() {
		for (GeoNode node : structure.getPermanentGeoGroup().getGeoNodes()) {
			node.getComponent().dispose();
		}
		structure.getPermanentGeoGroup().removeAllChildren();
	}

	private void readGroup() {
		char t;
		boolean hasMore = true;
		while(hasMore) {
			try {
				t = in.readChar();
				
				switch (t) {
				case 'T':
					readTube();
					break;
				case 'B':
					readBall();
					break;
				}
				
			} catch (IOException e) {
				hasMore = false;
			}
		}
		
	}

	private void readBall() throws IOException {
		double x = in.readDouble();
		double y = in.readDouble();
		double z = in.readDouble();
		char locked = in.readChar();
		char root = in.readChar();
		
		Ball ball = factory.createBall(new Point3d(x, y, z));
		if (locked == 'L')
			ball.lock();
		ball.setRoot(root == 'R');
		structure.addPermanentComponent(ball);
	}

	private void readTube() throws IOException {
		double x = in.readDouble();
		double y = in.readDouble();
		double z = in.readDouble();
		double yrot = in.readDouble();
		double zrot = in.readDouble();
		char locked = in.readChar();
		char root = in.readChar();
		
		Tube tube = factory.createTube(new Point3d(x, y, z), new Spherical(zrot, yrot));
		if (locked == 'L')
			tube.lock();
		tube.setRoot(root == 'R');
		structure.addPermanentComponent(tube);
		
	}


}
